<template>
    <div id="Message">
        <div class="container mt-4">
            <h4 class="mb-3">
                <b v-if="messageType==0"><i class="bi bi-pencil-square me-2"></i>普通消息</b>
                <b v-else><i class="bi bi-pencil-square me-2"></i>模板消息</b>
            </h4>

            <div class="composer-container">
                <form id="messageForm">
                    <div class="row">
                        <!-- 左侧主要编辑区 -->

                        <div class="col-md-8" v-if="messageType==0">
                            <el-form
                            ref="formRef"
                            style="max-width: 800px"
                            :model="normalForm"
                            label-width="auto"
                            class="demo-dynamic"
                            label-position="top"
                            >
                                <el-form-item prop="normalForm.title" label="标题">
                                    <el-input v-model="normalForm.title" size="large"/>
                                </el-form-item>
                                <!-- <el-form-item prop="normalForm.transactionType" label="消息类型">
                                    <el-radio-group v-model="normalForm.transactionType">
                                        <el-radio value="0" size="large">普通消息（未读/已读）</el-radio>
                                        <el-radio value="1" size="large">待办事项（未待办/已办）</el-radio>
                                    </el-radio-group>
                                </el-form-item> -->
                                <el-row :gutter="20">
                                    <el-col :span="12">
                                        <el-form-item prop="startTime" label="开始时间">
                                            <!-- <el-date-picker
                                            v-model="normalForm.startTime"
                                            type="date"
                                            placeholder="Pick a day"
                                            size="large"
                                            /> -->
                                            <el-date-picker
                                            v-model="normalForm.startTime"
                                            type="datetime"
                                            placeholder="Select date and time"
                                        />
                                        </el-form-item>

                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item prop="endTime" label="结束时间">
                                            <!-- <el-date-picker
                                            v-model="normalForm.endTime"
                                            type="date"
                                            placeholder="Pick a day"
                                            size="large"
                                            /> -->
                                            <el-date-picker
                                            v-model="normalForm.endTime"
                                            type="datetime"
                                            placeholder="Select date and time"
                                            />
                                        </el-form-item>

                                    </el-col>
                                </el-row>
                                <el-form-item prop="normalForm.groupIds" label="发送对象(组)">
                                    <el-select
                                    v-model="normalForm.groupIds"
                                    multiple
                                    style="width: 800px"
                                    placeholder="选择接收的组"
                                    size="large"
                                    >
                                    <el-option
                                        v-for="item in options"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value"
                                    />
                                    </el-select>
                                </el-form-item>
                                <el-form-item prop="normalForm.messageChild.templateContent" label="内容模板">
                                    <el-input
                                        v-model="normalForm.messageChild.templateContent"
                                        style="width: 800px"
                                        :autosize="{ minRows: 5, maxRows: 10 }"
                                        type="textarea"
                                        placeholder="Please input"
                                    />
                                </el-form-item>
                                <el-form-item prop="uploadRef" label="附件">
                                    <el-upload
                                        class="upload-file"
                                        ref="uploadRef"
                                        drag
                                        action="#"
                                        :limit="1"
                                        :http-request="uploadFile"
                                        :auto-upload="false"
                                    >
                                        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                                        <div class="el-upload__text">
                                        点击或拖拽文件到此处上传
                                        </div>
                                    </el-upload>
                                </el-form-item>
                            </el-form>
                        </div>
                        <div class="col-md-8" v-else>
                            <el-form
                            ref="templateFormRef"
                            style="max-width: 800px"
                            :model="normalForm"
                            label-width="auto"
                            class="demo-dynamic"
                            label-position="top"
                            >
                                <el-form-item prop="normalForm.title" label="模板标题">
                                    <el-input v-model="normalForm.title" size="large"/>
                                </el-form-item>
                                <el-form-item prop="normalForm.groupIds" label="发送对象(组)">
                                    <el-select
                                    v-model="normalForm.groupIds"
                                    multiple
                                    style="width: 800px"
                                    placeholder="选择接收的组"
                                    size="large"
                                    >
                                    <el-option
                                        v-for="item in options"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value"
                                    />
                                    </el-select>
                                </el-form-item>
                                <!-- <el-form-item prop="normalForm.messageChild.templateType" label="模板标题">
                                    <el-input v-model="normalForm.messageChild.templateType" size="large"/>
                                </el-form-item> -->
                                <el-form-item prop="uploadExcelRef" label="上传Excel数据">
                                    <el-upload
                                        class="upload-file"
                                        ref="uploadExcelRef"
                                        accept=".xlsx"
                                        drag
                                        action="#"
                                        :limit="1"
                                        :http-request="uploadExcel"
                                        :auto-upload="false"
                                    >
                                        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                                        <div class="el-upload__text">
                                        点击或拖拽文件到此处上传
                                        </div>
                                    </el-upload>
                                </el-form-item>
                                <!-- <el-form-item>
                                <el-link type="primary" underline="always" href="https://element-plus.org" target="_blank">下载模板</el-link>
                                </el-form-item> -->
                                <el-form-item prop="normalForm.messageChild.templateContent" label="内容模板">
                                    <el-input
                                        v-model="normalForm.messageChild.templateContent"
                                        style="width: 800px"
                                        :autosize="{ minRows: 5, maxRows: 10 }"
                                        type="textarea"
                                        placeholder="Please input"
                                    />
                                </el-form-item>
                                <el-form-item prop="uploadRef" label="附件">
                                    <el-upload
                                        class="upload-file"
                                        ref="uploadRef"
                                        drag
                                        action="#"
                                        :http-request="uploadFile"
                                        :auto-upload="false"
                                        :limit="1"
                                    >
                                        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                                        <div class="el-upload__text">
                                        点击或拖拽文件到此处上传
                                        </div>
                                    </el-upload>
                                </el-form-item>
                            </el-form>
                        </div>

                        <!-- 右侧选项与操作区 -->
                        <div class="col-md-4">
                            <div class="options-panel">
                                <h5 class="form-section-title">发送选项</h5>
                                <div class="mb-3">
                                    <!-- <label for="priority" class="form-label">重要程度</label>
                                    <select v-model="normalForm.importance" class="form-select form-select-sm" id="priority">
                                        <option value="普通" selected>普通</option>
                                        <option value="重要">重要</option>
                                        <option value="紧急">紧急</option>
                                    </select> -->
                                    <label for="priority" class="form-label">重要程度</label>
                                    <el-select
                                    v-model="normalForm.importance"
                                    placeholder="选择重要程度"
                                    size="large"
                                    id="priority"
                                    >
                                    <el-option
                                        v-for="item in important"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value"
                                    />
                                    </el-select>
                                </div>
                                <div class="mb-3">
                                    <label for="transaction_type" class="form-label">事务类型</label>
                                    <el-select
                                    v-model="normalForm.transactionType"
                                    placeholder="选择事务类型"
                                    size="large"
                                    id="transaction_type"
                                    >
                                    <el-option
                                        v-for="item in template_type"
                                        :key="item.value"
                                        :label="item.label"
                                        :value="item.value"
                                    />
                                    </el-select>
                                </div>

                                <div id="taskSpecificOptions" class="mb-3" style="display: none;"> <!-- Only show for task/approval/meeting -->
                                    <label for="deadline" class="form-label">截止日期/会议时间</label>
                                    <input type="datetime-local" class="form-control form-control-sm" id="deadline">
                                </div>
                                <hr>
                                <div class="d-grid gap-2">
                                    <button type="button" class="btn btn-primary" @click="handleNormalMessage"><i class="bi bi-send-fill me-1"></i>立即发送</button>
                                </div>
                            </div>
                        </div>
                    </div>
                </form>
            </div>
        </div>

    </div>
</template>
<script setup>
import { UploadFilled } from '@element-plus/icons-vue'
import { ref,reactive, watch, onMounted } from 'vue';
import { Modal } from 'bootstrap/dist/js/bootstrap.bundle.min';
import { useMessageStore } from '@/stores/Message';
import { useRouter } from 'vue-router' // 1. 引入 useRouter
import { useDataStore } from '@/stores/File';
import { ElMessage } from 'element-plus';
import { addLog } from '@/api/log';
const uploadRef = ref();
const uploadExcelRef = ref();
const uploadRefFile = ref();
const router = useRouter() // 2. 获取 router 实例
const props = defineProps(['id'])
const formRef = ref()
const templateFormRef = ref()
const messageType = ref(props.id!=0?true:false)
const messageStore = useMessageStore();
const dataStore = useDataStore();
const fileId = reactive({
    id:''
})
const currentUser = ref(JSON.parse(localStorage.getItem('userInfo')));

const flag = reactive({
    file:false,
    excel:false
})  // 是否有文件

const templateData = `
    收到来自#{组}的#{消息类型}：
    标题：#{标题}
    详情：关键课程组会议，
    时间：2025年3月21日，
    地点：A11-102
`
const important = [
    {
        value: '普通',
        label: '普通',
    },
    {
        value: '重要',
        label: '重要',
    },
    {
        value: '紧急',
        label: '紧急',
    },
]
const template_type = [
  {
    value: '教学事务',
    label: '教学事务',
  },
  {
    value: '教科研事务',
    label: '教科研事务',
  },
  {
    value: '学科竞赛',
    label: '学科竞赛',
  },
  {
    value: '学习培训',
    label: '学习培训',
  }
]

// 普通消息
const normalForm = reactive({
    title: "",
    transactionType: "",
    groupIds: [],
    status: "未读",
    importance: "",
    senderUserId: currentUser.value.userId,
    sendTime: "2025-06-18",
    startTime:'',
    endTime: "",
    messageChild: {
        templateType: "",
        templateContent: templateData,
        scheduledTime: "",
        template: props.id==='1'?true:false
    },
    file: {
        excelData:null,
        fileData:null
    },
},)
// 模板消息
const templateForm = reactive({
    type:'',
    excel:'',
    template:templateData,
    uploadRef:'',
    priority:'',
})


const options = reactive(messageStore.GroupList)

const uploadFile = async(data)=>{
    console.log("send file~~");
    const fileData = new FormData();
    fileData.append('fileData',data.file);
    fileData.append('id',fileId.id);
    await dataStore.sendFile(fileData).then(res=>{
        if (res.code===1&&props.id==='0') {
            router.push("/message")
        }
    })
}

const handleSuccess = (data)=>{
    console.log(1111);

    if (data==='file') {
        flag.file = true
    }else if(data==='excel'){
        flag.excel = true
    }
}
const removeFile = (data)=>{
    console.log(2222);

    if (data==='file') {
        flag.file = false;
    }else if(data==='excel'){
        flag.excel = false
    }
}

const uploadExcel = async(data)=>{
    console.log("send excel~~");
    const excelData = new FormData();
    excelData.append('excelData',data.file);
    excelData.append('id',fileId.id);
    await dataStore.sendExcel(excelData).then(res=>{
        console.log("excel==>");
        console.log(res);

        if (res.code===1&&props.id==='1') {
            router.push("/message")
        }
    })
}



const submitForm = (formEl) => {
  if (!formEl) return
  console.log(normalForm);
}

const resetForm = (formEl) => {
  if (!formEl) return
  formEl.resetFields()
}
// 提交消息
const handleNormalMessage = async () => {

    const logInfo = {
        userId: normalForm.senderUserId,
        userName: '管理员',
        module: '消息发送中心',
        actionType: normalForm.messageChild.template ? '发送模板消息' : '发送普通消息',
        actionName: normalForm.title
    };
    try {
        const res = await messageStore.addItem(normalForm).then(res=>{
            if (res.code===1) {
                ElMessage({
                    message: '添加成功',
                    type: 'success',
                })
                fileId.id = res.data
                uploadRef.value.submit();
                if (props.id==='1') {
                    uploadExcelRef.value.submit()
                }
            }
            return res
        })
        if (res && res.code === 1) {
            // ElMessage({ message: '添加成功', type: 'success' });
            
            try {
                await addLog({ ...logInfo, status: '成功' });
                console.log(logInfo)
            } catch (logError) { // <--- 确保这个 catch 存在
                console.error("记录成功日志失败，但不影响主流程:", logError);
            }
        } else {
            ElMessage({ message: `添加失败: ${res?.message || '未知业务错误'}`, type: 'error' });
            try {
                await addLog({ ...logInfo, status: '失败' });
            } catch (logError) { // <--- 确保这个 catch 存在
                console.error("记录业务失败日志时出错:", logError);
            }
        }

    } catch (error) { // <--- 这是最外层 try 对应的 catch
        ElMessage({ message: '服务异常，请检查网络或联系管理员', type: 'error' });
        try {
            await addLog({ ...logInfo, status: '失败' });
        } catch (logError) { // <--- 确保这个 catch 存在
            console.error("记录网络异常日志时出错:", logError);
        }

        console.error("发送消息时捕获到严重错误:", error);
    }
};

watch(messageType,()=>{
    console.log(messageType.value);

    if (messageType.value) {
        return router.push("/send/1")
    }
    else return router.push("/send/0")
})

// onMounted(()=>{
//     messageStore.HandleGroups(10000001);
// })

</script>
<style scoped>
    #Message { background-color: #f8f9fa; }
    .label-text {
        display: block;
        width: 200px;
    }
    .navbar-brand img { filter: brightness(0) invert(1); }
    .composer-container {
        background-color: #fff;
        padding: 25px;
        border-radius: 8px;
        box-shadow: 0 2px 10px rgba(0,0,0,0.1);
    }
    .options-panel {
        background-color: #f8f9fa;
        padding: 20px;
        border-radius: 8px;
        border: 1px solid #dee2e6;
    }
    .form-section-title {
        font-size: 1.1rem;
        font-weight: 500;
        color: #0d6efd; /* Primary color */
        margin-bottom: 15px;
        padding-bottom: 5px;
        border-bottom: 2px solid #0d6efd;
    }
    .uploaded-files .badge { cursor: pointer; }
    .upload-file {width: 800px;}
</style>
